<?php
/**
 * Created by PhpStorm.
 * User: yuyiwen
 * Date: 2018/10/26
 * Time: 上午9:45
 */

namespace app\admin\controller;


use think\Image;
use think\Request;

class Ad extends Common
{
    public function index ()
    {
        // 判断用户是否有搜索
        $search = input('get.search' , '' , 'htmlspecialchars');
        $page = input('get.page' , '1');
        $ad = db('ad');
        $config = [];
        $config['page'] = $page;
        if ($search != '')
        {
            $config ['query'] =['search' =>$search ];
           $ad->whereLike('url' , "%{$search}%");
        }

        $ad_list =$ad->paginate(3 , false , $config);
        $data = $ad_list->toArray();
        if (empty($data['data'])) {
            $config['page'] = $config['page'] - 1 > 1 ? $config['page'] - 1 : 1;
            $ad_list =$ad->paginate(3 , false , $config);
        }

        $page  = $ad_list->render();
        $search = ['pagination' , 'disabled' , 'active'];
        $replace = ['am-pagination tpl-pagination' , 'am-disabled' , 'am-active'];
        $page = str_replace($search , $replace , $page);

        $request = Request::instance();
        if ($request -> isAjax()) {
            return json(['ad_list' => $ad_list , 'page' => $page]);
        }else {
            $this->assign('page', $page);
            $this->assign('ad_list', $ad_list);
            return view();
        }
    }

    public function delete () {
        $id = input('get.id');
        $affectedRow = db('ad')->where('id' , $id)->delete();
        if ($affectedRow) {
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }
    }

    public function insert () {
        return view();
    }

    public function store () {
        $post = input('post.');
        // 使用验证器验证数据
        $ad = validate('Ad');

        if (!$ad->check($post)) {
            $this->error( $ad->getError() );
            die;
        }

        // 上传图片
        $file = request()->file('src');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $post['src'] =  $info->getSaveName();

                // 制作缩略图
                $image = Image::open(ROOT_PATH . 'public' . DS . 'uploads' . '/' .$info->getSaveName());
                $dir = dirname(ROOT_PATH . 'public' . DS . 'thumbs/'.$info->getSaveName());
                !file_exists($dir) && mkdir($dir , 0777 , true) ;

                $image->thumb(150, 150)->save(ROOT_PATH . 'public' . DS . 'thumbs/'.$info->getSaveName());

            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }




        // 插入数据库
        $insertId = db('ad')->insertGetId($post);
        if ($insertId) {
            $this->success('插入成功' , url('index'));
        }else {
            $this->error('插入失败');
        }


    }

    public function edit () {

        $id = input('get.id' , '' , 'intval');
        $info = db('ad')->find($id);
        $this->assign('info' , $info);
        return view();
    }

    public function save () {
        $post = input('post.');

        // 使用验证器验证数据
        $ad = validate('Ad');

        if (!$ad->check($post)) {
            $this->error( $ad->getError() );
            die;
        }

        // 上传图片
        $file = request()->file('src');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){

            // 查出原来的图片，如果原来的图片存在。则删除它
            $info = db('ad')->find($post['id']);
            if (file_exists(ROOT_PATH . 'public' . DS . 'uploads' . '/' .$info['src'])) {
                unlink(ROOT_PATH . 'public' . DS . 'uploads' . '/' .$info['src']);
            }
            if (file_exists(ROOT_PATH . 'public' . DS . 'thumbs' . '/' .$info['src'])) {
                unlink(ROOT_PATH . 'public' . DS . 'thumbs' . '/' .$info['src']);
            }

            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $post['src'] =  $info->getSaveName();

                // 制作缩略图
                $image = Image::open(ROOT_PATH . 'public' . DS . 'uploads' . '/' .$info->getSaveName());
                $dir = dirname(ROOT_PATH . 'public' . DS . 'thumbs/'.$info->getSaveName());
                !file_exists($dir) && mkdir($dir , 0777 , true) ;

                $image->thumb(150, 150)->save(ROOT_PATH . 'public' . DS . 'thumbs/'.$info->getSaveName());

            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }


        db('ad')->update($post);

        $this->success('更新成功' , url('index'));
        // 插入数据库
//        $insertId = db('ad')->insertGetId($post);
//        if ($insertId) {
//            $this->success('插入成功' , url('index'));
//        }else {
//            $this->error('插入失败');
//        }
    }
}